<template>
	<view class="sucai">
		<view class="header">
			<uniNavBar title="素材"></uniNavBar>
			<view class="search">
				<input @tap="changeMask" @focus="resetTag" @input="changeInput" :value="searchValue" placeholder="请输入搜索内容" class="search-input" />
				<view class="search-btn" @tap="getSearch"><image class="search-icon" src="../../static/img/search_iconss@2x.png"></image></view>
			</view>
			<view class="types" v-show="showArr.length">
				<view
					:class="`type-item ${activeKey === item.tagId ? 'active-key' : ''}`"
					v-for="(item, i) in showArr"
					:key="item.tagId"
					@tap="changeActivekey(item.tagId, item.tagName)"
				>
					{{ item.tagName }}
				</view>
				<view class="item-arrow" v-show="(this.typeArr > this.showArr || this.line === -1) && showArr.length !== 0">
					<image :class="`arrow ${showMask ? 'arrow-down' : ''}`" @tap="upDown" src="/static/h5img/arrowdown_search@2x.png"></image>
				</view>
			</view>
			<view class="mask" @tap="hideMask" v-if="showMask"></view>
		</view>
		<view :class="`sucai-content ${showArr.length ? (line === 1 ? 'sucai-line1' : 'sucai-line2') : 'sucai-line0'}`">
			<!-- 素材列表 -->
			<view class="collect-list" v-if="sourceData.length">
				<view class="collect-item" v-for="(item, i) in sourceData" :key="`content-${i}`">
					<view class="item-top">
						<image class="business-img" :src="`https://static.xpandago.net/${item.brandImg}`"></image>
						<text class="business-title">{{ item.title }}</text>
					</view>
					<view class="item-content">
						<view class="item-description">{{ item.content }}</view>
						<view class="item-img-box">
							<view class="img-box" v-for="(img, ind) in item.imgArray" :key="`cc${ind}`" @tap="previewImg(item.imgArray, ind)">
								<image mode="aspectFit" class="item-img" :src="`https://static.xpandago.net/${img}`"></image>
							</view>
						</view>
						<view class="tags">
							<view class="tag-item" v-for="(tag, index) in item.tagArray" :key="index">{{ tag }}</view>
						</view>
						<view class="item-footer">
							<text class="item-time">{{ item.createTime }}</text>
							<view class="operate-btn">
								<view class="collect" @tap="collectSource(item.materialId, i)">
									<image class="collect-btn" :src="item.collectFlag === '1' ? '/static/h5img/shoucang_select@2x.png' : '/static/h5img/shoucang@2x.png'"></image>
									<text>收藏</text>
								</view>
								<view
									class="down-load"
									v-clipboard:copy="item.content"
									v-clipboard:success="type => onCopyResult('success', item)"
									v-clipboard:error="type => onCopyResult('error')"
								>
									<image class="down-load-btn" src="/static/h5img/download@2x.png"></image>
									<text>下载</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="default-Page" v-show="!sourceData.length"><image src="../../static/h5img/default_04@2x.png" class="default4"></image></view>
		</view>
		<!-- 微信朋友圈地址未知，赞不开发 -->
		<!-- <view><a href="javascript:window.location.href='weixin://'">分享</a></view> -->
	</view>
</template>

<script>
import api from '@/common/api';
import { ifLogin } from '@/common/js/index'
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
export default {
	data() {
		return {
			activeKey: 0, // active标签
			showMask: false, //是否展示mask
			searchValue: '', // 查询条件
			showNum: 0, // 可展示的关键词数量
			typeArr: [],
			showArr: [],
			token: '',
			line: -1,
			limit: 2,
			page: 1,
			pageCount: 0,
			sourceData: [] // 素材列表
		};
	},
	methods: {
		resetTag() {
			const _this = this
			if (_this.activeKey) {
				_this.activeKey = 0
			}
		},
		// 图片预览
		previewImg(urlArr, index) {
			const arr = urlArr.map(url => {
				return `https://static.xpandago.net/${url}`
			})
			uni.previewImage({
				urls: arr,
				current:index,
			});
		},
		downImg(imgArr) {
			const that = this;
			imgArr.forEach(src => {
				// uni.downloadFile({
				// 	url: `https://static.xpandago.net/${src}`,
				// 	success: res => {
				// 		if (res.statusCode === 200) {
				// 			that.saveImg(res.tempFilePath);
				// 		}
				// 	}
				// });
				
			});
		},
		saveImg(url) {
			var oA = document.createElement('a');
			oA.download = ''; // 设置下载的文件名，默认是'下载'
			oA.href = url;
			document.body.appendChild(oA);
			oA.click();
			oA.remove(); // 下载之后把创建的元素删除
		},
		getContentDisposition(fileName, fileType) {
		  return `attachment; filename=${encodeURIComponent(fileName)}.${fileType}; filename*=utf-8''${encodeURIComponent(fileName)}.${fileType};`
		},
		async collectSource(materialId, index) {
			const _this = this;
			const data = {};
			if (materialId) {
				data.materialId = materialId;
			}
			const [err, res] = await api.sourceCollect({
				method: 'post',
				header: {
					'Content-Type': 'application/json;charset=UTF-8',
					token: _this.token
				},
				query: data
			});
			if (res && res.data) {
				const { data = {} } = res;
				if (data.code === 0 && data.data) {
					_this.sourceData.splice(index, 1, data.data);
				}
			}
		},
		changeActivekey(key, value) {
			this.activeKey = key;
			this.searchValue = value;
			this.page = 1;
			this.pageCount = 0;
			this.sourceData = [];
			if (this.showMask) {
				this.showMask = !this.showMask;
				this.computedWidth();
			}
			this.getSourceList();
		},
		hideMask() {
			this.showMask = !this.showMask;
			this.computedWidth();
		},
		upDown() {
			this.showMask = !this.showMask;
			if (this.showMask) {
				this.showArr = this.typeArr;
				this.line = -1;
			} else {
				this.computedWidth();
			}
		},
		async onCopyResult(type, item) {
			if (type === 'success') {
				const copy = await this.sourceDownload(item);
				this.downImg(item.imgArray);
				uni.showToast({
					title: copy ? '文本已复制' : '下载失败',
					icon: 'none'
				});
			} else {
				if (type === 'error') {
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					});
				}
			}
		},
		computedWidth() {
			let _this = this;
			let lineWith1 = 0;
			let lineWith2 = 0;
			let count = 0;
			let lineNum = -1;
			const query = uni.createSelectorQuery().in(this);
			const { windowWidth } = uni.getSystemInfoSync();
			const typeWidth = windowWidth - 20;
			query.selectAll('.types .type-item').boundingClientRect();
			query.selectViewport().scrollOffset();
			query.exec(function(res) {
				if (res[0].length) {
					lineNum = 1;
				}
				for (let n = 0; n < res[0].length; n++) {
					if (lineWith1 <= typeWidth && lineNum === 1) {
						lineWith1 = lineWith1 + Number(res[0][n].width) + 10;
						if (lineWith1 <= typeWidth) {
							count += 1;
						} else {
							lineNum = 2;
						}
					}
					if (lineWith2 <= typeWidth && lineNum === 2) {
						lineWith2 = lineWith2 + Number(res[0][n].width) + 10;
						if (lineWith2 + 10 <= typeWidth) {
							count += 1;
						}
					}
				}
				_this.line = lineNum;
				_this.showNum = count;
				_this.showArr = _this.typeArr.slice(0, count);
			});
		},
		changeMask() {
			if (!this.showMask) {
				this.showMask = !this.showMask;
				this.showArr = this.typeArr;
			}
		},
		getSearch() {
			this.page = 1;
			this.pageCount = 0;
			this.sourceData = [];
			if (this.showMask) {
				this.showMask = !this.showMask;
				this.computedWidth();
			}
			this.getSourceList();
		},
		changeInput(e) {
			this.searchValue = e.target.value;
		},
		async getTags() {
			const _this = this;
			_this.token = uni.getStorageSync('token');
			const [err, res] = await api.material({
				method: 'get',
				header: {
					'Content-Type': 'application/json;charset=UTF-8',
					token: _this.token
				}
			});
			if (res) {
				const { data = {} } = res;
				if (data.code === 0 && data.data && data.data.length) {
					_this.typeArr = data.data;
					// _this.activeKey = data.data[0].tagId;
				}
			} else {
				_this.typeArr = [];
			}
			_this.showNum = _this.typeArr.length;
			_this.showArr = _this.typeArr;
		},
		async getSourceList() {
			const _this = this;
			const data = {
				limit: _this.limit,
				page: _this.page
			};
			if (_this.activeKey) {
				data.tagId = _this.activeKey;
			}
			if (_this.searchValue) {
				data.searchContent = _this.searchValue;
			}
			const [err, res] = await api.materialList({
				method: 'get',
				header: {
					'Content-Type': 'application/json;charset=UTF-8',
					token: _this.token
				},
				query: data
			});
			if (res) {
				const { data = {} } = res;
				if (data.data && data.data.list && data.data.list.length) {
					_this.sourceData = [..._this.sourceData, ...data.data.list];
				}
				if (data.data && data.data.totalPage) {
					_this.pageCount = data.data.totalPage;
				}
			}
		},
		async sourceDownload(item) {
			const data = {};
			if (item.materialId) {
				data.materialId = item.materialId;
			}
			const [err, res] = await api.sourceDownload({
				method: 'post',
				header: {
					'Content-Type': 'application/json;charset=UTF-8',
					token: this.token
				},
				query: data
			});
			let copy = false;
			if (res) {
				const { data = {} } = res;
				if (data.code === 0) {
					copy = true;
				}
			}
			return copy;
		}
	},
	components: {
		uniNavBar
	},
	async onLoad() {
		const status = ifLogin()
		if (status) {
			await this.getTags();
			this.getSourceList();
			this.computedWidth();
		}
	},
	onReady() {
		this.computedWidth();
	},
	onReachBottom() {
		if (this.pageCount > this.page) {
			this.page += 1;
			this.getSourceList();
		}
	}
};
</script>

<style scoped lang="scss">
body,
uni-page-body {
	background-color: #f7f7f7;
}
.sucai {
	background-color: #f7f7f7;
	height: 100%;
	.header {
		position: fixed;
		width: 100%;
		z-index: 10;
		height: fit-content;
		.search {
			display: flex;
			background-color: #fff;
			padding: 20rpx 30rpx 8rpx 30rpx;
			align-items: center;
			font-size: 28rpx;
			padding-left: 28rpx;
			.search-input {
				flex: 1;
				height: 66rpx;
				border: 1rpx solid #ededed;
				border-radius: 4rpx 0 0 4rpx;
				.uni-input-placeholder {
					font-family: PingFang-SC-Medium;
					color: #ddd;
					font-size: 28rpx;
					padding-left: 28rpx;
				}
				/deep/ .uni-input-input {
					font-size: 28rpx;
					padding-left: 28rpx;
					color: #333;
				}
			}
			.search-btn {
				width: 142rpx;
				height: 66rpx;
				background-color: #322f2c;
				display: flex;
				align-items: center;
				justify-content: center;
				.search-icon {
					height: 32rpx;
					width: 32rpx;
				}
			}
		}
		.types {
			display: flex;
			flex-wrap: wrap;
			background-color: #fff;
			padding: 0 20rpx 22rpx 20rpx;
			transition: 0.3s;
			.item-arrow {
				margin: 22rpx 10rpx 0 10rpx;
				height: 60rpx;
				line-height: 60rpx;
				.arrow {
					height: 60rpx;
					width: 60rpx;
					transform: rotate(180deg);
					&.arrow-down {
						transform: rotate(0);
					}
				}
			}
			.type-item {
				height: 58rpx;
				line-height: 58rpx;
				font-family: PingFang-SC-Medium;
				font-size: 26rpx;
				color: #333;
				padding: 0 22rpx;
				border-radius: 30rpx;
				border: 1rpx solid #fff;
				margin: 22rpx 10rpx 0 10rpx;
				background-color: #f7f7f7;
				&.active-key {
					border: 1rpx solid #dbc291;
					background-color: #f8f5ee;
				}
			}
		}
		.mask {
			display: block;
			height: 1000px;
			background-color: rgba(33, 33, 33, 0.5);
			z-index: 2;
			overflow: hidden;
		}
	}
	.sucai-content {
		box-sizing: border-box;
		padding-bottom: 40rpx;
		height: 100%;
		&.sucai-line1::before {
			height: 292rpx;
			display: block;
			content: '';
		}
		&.sucai-line2::before {
			height: 374rpx;
			display: block;
			content: '';
		}
		&::before {
			height: 94px;
			display: block;
			content: '';
		}
		.default-Page {
			height: 100%;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #f7f7f7;
			.default4 {
				height: 560rpx;
				width: 440rpx;
				margin-top: 80rpx;
			}
		}
		.collect-list {
			margin-top: 20rpx;
			padding: 0 30rpx;
			background-color: #fff;
			display: block;
			.collect-item {
				&:not(:last-child) {
					border-bottom: 1px solid #ededed;
				}
				.item-top {
					padding-top: 30rpx;
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;
					.business-img {
						height: 64rpx;
						width: 64rpx;
						border-radius: 50%;
						margin: 0 16rpx 0 4rpx;
					}
					.business-title {
						font-family: PingFang-SC-Medium;
						font-size: 26rpx;
						color: #333333;
					}
				}
				.item-content {
					padding-left: 86rpx;
					.item-description {
						font-family: PingFang-SC-Medium;
						line-height: 40rpx;
						font-size: 26rpx;
						color: #333;
						margin-bottom: 7rpx;
						word-break: break-all;
					}
					.item-img-box {
						display: flex;
						flex-wrap: wrap;
						.img-box {
							width: 33.3%;
							display: flex;
							&:nth-child(3n + 2) {
								justify-content: space-around;
							}
							&:nth-child(3n) {
								justify-content: flex-end;
							}
						}
						.item-img {
							height: 186rpx;
							width: 186rpx;
							margin-top: 21rpx;
						}
					}
				}
				.tags {
					display: flex;
					flex-wrap: wrap;
					align-items: center;
					margin-left: -12rpx;
					.tag-item {
						border: 1rpx solid #ddd;
						height: 46rpx;
						margin-top: 25rpx;
						border-radius: 20rpx;
						padding: 0 24rpx;
						margin-left: 16rpx;
						font-size: 26rpx;
						font-family: PingFang-SC-Medium;
						color: #999;
					}
				}
				.item-footer {
					margin-left: 4rpx;
					margin-top: 11rpx;
					padding-bottom: 40rpx;
					display: flex;
					justify-content: space-between;
					color: #999;
					.item-time {
						font-size: 22rpx;
						line-height: 40rpx;
					}
					.operate-btn {
						display: flex;
						.collect {
							font-size: 22rpx;
							margin-right: 21rpx;
							display: flex;
							align-items: center;
							.collect-btn {
								height: 25rpx;
								width: 25rpx;
								margin-right: 12rpx;
							}
						}
						.down-load {
							font-size: 22rpx;
							display: flex;
							align-items: center;
							.down-load-btn {
								width: 24rpx;
								height: 24rpx;
								margin-right: 12rpx;
							}
						}
					}
				}
			}
		}
	}
}
</style>
